package com.avyss.flyingpoints.scene;

public class Leader extends AbstractFlyingObject {

	private float leaderDirection;			//(radians) 
	private long  timeSinceDirectionChange;	//(msecs)
	
	public Leader(DynamicsParams params) {
		super(params);
		
	    // Give random initial direction to the leader
	    forceRandomDir();
	}

	public void forcePlacement(float posX, float posY) {
		this.posX = posX;
		this.posY = posY;
	}
	
	public void forceRandomDir() {
	    leaderDirection = (float) (2 * Math.PI * rand.nextFloat());
	    velX = (float) (0.85 * params.getMaxVelocity() * Math.cos(leaderDirection));
	    velY = (float) (0.85 * params.getMaxVelocity() * Math.sin(leaderDirection));
	    timeSinceDirectionChange = 0;
	}
	
	public void applyMove(long timeStepMs) {
		super.applyMove(timeStepMs);
		
	    // Check if leader hit the border
	    if ((posX < 0) || (posX >= params.getWindowWidth())) {
	    	 if (posX < 0) {
	    		 velX = Math.abs(velX);
	    	 } else {
	    		 velX = - Math.abs(velX);
	    	 }
	         timeSinceDirectionChange = 0;
	         leaderDirection = (float) Math.atan2(velY, velX);
	    }
	    if ((posY < 0) || (posY >= params.getWindowHeight())) {
	    	 if (posY < 0) {
	    		 velY = Math.abs(velY);
	    	 } else {
	    		 velY = - Math.abs(velY);
	    	 }
	         timeSinceDirectionChange = 0;
	         leaderDirection = (float) Math.atan2(velY, velX);
	    }
	}	

	public void adjustVelociyLeader(long timeStepMs) {
		timeSinceDirectionChange += timeStepMs;
	    if (timeSinceDirectionChange > params.getLeaderDirectionChangeTime()) {
	    	timeSinceDirectionChange = 0;

	    	float dirIncr = (float) (params.getLeaderDeflectionAngle() / 180.0 * Math.PI);
			if (rand.nextBoolean()) {
				leaderDirection = leaderDirection + dirIncr;
			} else {
				leaderDirection = leaderDirection - dirIncr;
			}
			
			velX = (float) (0.85 * params.getMaxVelocity() * Math.cos(leaderDirection));
			velY = (float) (0.85 * params.getMaxVelocity() * Math.sin(leaderDirection));
	    }
	}
}
